package top.mask.mq.dead;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.CancelCallback;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.DeliverCallback;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import top.mask.mq.utils.RabbitMQUtil;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;

/**
 * 死信队列实战
 * 消费者1
 * 成为死信：
 * 1.消息被拒绝
 * 2.消息TTL过期
 * 3.队列达到最大长度
 */
@Slf4j
public class Consumer01 {
    //普通交换机名称
    public static final String NORMAL_EXCHANGE = "normal_exchange";

    //死信队列交换机名称
    public static final String DEAD_EXCHANGE = "dead_exchange";

    //普通队列名称
    public static final String NORMAL_QUEUE = "normal_queue";

    //死信队列名称
    public static final String DEAD_QUEUE = "dead_queue";

    @SneakyThrows
    public static void main(String[] args) {
        Channel channel = RabbitMQUtil.getChannel();
        //声明普通交换机类型为direct
        channel.exchangeDeclare(NORMAL_EXCHANGE, BuiltinExchangeType.DIRECT);
        //声明死信交换机类型为direct
        channel.exchangeDeclare(DEAD_EXCHANGE, BuiltinExchangeType.DIRECT);

        //声明普通队列
        HashMap<String, Object> arguments = new HashMap<>();
        //过期时间
        arguments.put("x-message-ttl",10000);
        //正常队列设置死信交换机
        arguments.put("x-dead-letter-exchange",DEAD_EXCHANGE);
        //设置死信RoutingKey
        arguments.put("x-dead-letter-routing-key","lisi");
        //设置队列最大长度
        arguments.put("x-max-length",6);
        channel.queueDeclare(NORMAL_QUEUE,false,false,false,null);
        //声明死信队列
        channel.queueDeclare(DEAD_QUEUE,false,false,false,null);

        //绑定普通的交换机与队列
        channel.queueBind(NORMAL_QUEUE,NORMAL_EXCHANGE,"zhangsan");
        //绑定死信的交换机与死信的队列
        channel.queueBind(DEAD_QUEUE,DEAD_EXCHANGE,"lisi");
        log.info("等待接收消息...");

        DeliverCallback deliverCallback = (consumerTag, message) -> {
            String msg = new String(message.getBody(), "UTF-8");
            if (msg.equals("info5")){
                //拒绝消息
                log.info("Consumer01死信队列接收到的消息:[{}],此消息是被C1拒绝的",msg);
                channel.basicReject(message.getEnvelope().getDeliveryTag(),false);
            }else {
                log.info("Consumer01死信队列接收到的消息:[{}]",msg);
                channel.basicAck(message.getEnvelope().getDeliveryTag(),false);
            }


        };

        CancelCallback cancelCallback = consumerTag ->
                log.info("消息者取消消接口回调逻辑{[]}",consumerTag);

        //开启手动应答
        channel.basicConsume(NORMAL_QUEUE,false,deliverCallback,cancelCallback);
    }
}
